package com.holly.unit.auth.auth;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.holly.unit.auth.api.LoginRecordService;
import com.holly.unit.auth.api.pojo.auth.LoginRecord;
import com.holly.unit.cache.api.CacheOperatorApi;
import com.holly.unit.config.api.context.ConfigContext;
import com.holly.unit.system.api.constants.SystemConstants;
import com.holly.unit.system.api.pojo.user.HisUserPasswordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import static com.holly.unit.auth.api.constants.AuthConstants.LOGGED_LOCKED_PREFIX;

@Service
public class LoginRecordServiceImpl implements LoginRecordService {
    @Autowired
    private ApplicationContext context;

    @Resource(name = "loginRecordCache")
    private CacheOperatorApi<LoginRecord> cacheLoginRecordApi;

    public LoginRecord getUseLoginByUsername(String username) {
        LoginRecord record = cacheLoginRecordApi.get(username);
        return record;
    }

    public LoginRecord saveOrUpdateUserLogin(LoginRecord loginRecord) {
        //超过锁定时间，自动解锁
        int lockedTime = ConfigContext.me().getSysConfigValueWithDefault(SystemConstants.LOCKED_TIME, Integer.class, 30);
        cacheLoginRecordApi.put( loginRecord.getUsername(), loginRecord, lockedTime * 60L);
        return loginRecord;
    }

    public void unlockedByUsername(String username) {
        cacheLoginRecordApi.remove(username);
    }
}
